/**
 * Created by leo on 3/10.
 */
(function () {
    "use strict";
    angular.module("QuickSearch", ['Shortcut'])
        .directive("quickSearch", function ($http, urlPrefix, tabService, ShortcutService, parseHost) {
            return {
                restrict: 'A',
                scope: {},
                link: function (scope, elem) {
                    scope.placeholder = "便捷搜索";
                    scope.suggestions = [];
                    scope.highlightText = function (text, keyword) {
                        return text.replace(keyword, '<b>' + keyword + '</b>');
                    };
                    scope.tabService = tabService;
                    scope.clickSuggestion = function (sg) {
                        tabService.addTab({name: sg.text, url: parseHost(sg.url)});
                    };
                    scope.suggestionType = function (sg) {
                        return {'menu': '功能菜单', 'shortcut': '快捷收藏'}[sg.type];
                    };
                    var keyMap = {
                        'UP': 38,
                        'DOWN': 40,
                        'ENTER': 13,
                        'ESC': 27
                    };
                    scope.onKeyUp = function (e) {
                        if (e.keyCode == keyMap.UP || e.keyCode == keyMap.DOWN) { // up or down 调整光标位置
                            var currentIndex = (scope.suggestions._currentIndex || 0) + (e.keyCode == 38 ? -1 : 1);
                            scope.suggestions._currentIndex = currentIndex < 0 ?
                            currentIndex + scope.suggestions.length : currentIndex % scope.suggestions.length;
                        } else if (e.keyCode == keyMap.ENTER) { // 回车操作 触发点击动作（打开tab）
                            scope.onEnter();
                        } else if (e.keyCode == keyMap.ESC) { // 失去焦点
                            angular.element(':text', elem).blur();
                        } else { // 可见字符 重新查询搜索
                            scope.searchSuggestions(e.target.value);
                        }
                    };

                    scope.onEnter = function () {
                        var suggestion = scope.suggestions[scope.suggestions._currentIndex || 0];
                        if (suggestion) {
                            scope.clickSuggestion(suggestion);
                            scope.closeSuggestions();
                        }
                    };

                    var shortcutsChangeListener = function () {
                        var shortcuts = this;
                        if (shortcuts.length > 0) {
                            angular.forEach(shortcuts, function (shortcut) {
                                this.push({
                                    text: shortcut.shortcutName,
                                    type: 'shortcut',
                                    url: shortcut.shortcutPath
                                });
                            }, scope.suggestions = []);
                        } else {
                            scope.suggestions = [{text: '您还没有添加快捷搜藏！'}];
                        }
                    };

                    scope.closeSuggestions = function () {
                        ShortcutService.removeChangeListener(shortcutsChangeListener);
                        // 清除搜索建议
                        scope.suggestions = [];
                    };
                    scope.searchSuggestions = function (keyword) {
                        var limit = 10;
                        if (keyword.length > 0) {
                            $http.get(urlPrefix + "/menusSearch.do", {
                                params: {keyword: keyword, limit: limit},
                                cache: true
                            }).success(function (results) {
                                if (results.length > limit) results.length = limit;
                                angular.forEach(results, function (menu) {
                                    this.push({
                                        text: menu.MODULE_NAME,
                                        id: menu.MODULE_ID,
                                        type: 'menu',
                                        url: parseHost(menu.MODULE_PATH)
                                    });
                                }, scope.suggestions = []);
                            });
                            ShortcutService.removeChangeListener(shortcutsChangeListener);
                        } else {
                            ShortcutService.getShortcuts().then(function (shortcuts) {
                                shortcutsChangeListener.call(shortcuts);
                            });
                            ShortcutService.addChangeListener(shortcutsChangeListener);
                        }
                    };

                    scope.isRemoveShortcut = function (isMouseInSGType, sg) {
                        return isMouseInSGType && sg.type == 'shortcut';
                    };
                    scope.removeShortcut = function (url) {
                        ShortcutService.removeShortcut(url);
                        // 使搜索框获取光标，以便在点击其他地方能触发器blur事件
                        angular.element(':text', elem).focus();
                    };

                    angular.element('body').on('keydown', function (e) {
                        // 快捷键Ctrl+Q将光标定位到便捷搜索框
                        if (e.keyCode == 81 && e.ctrlKey) {
                            elem.find(':text').focus().select();
                        }
                    });
                },
                templateUrl: 'app/quick-search/quick-search.html',
                replace: true
            };
        });
})();